package com.huayue.dao;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.huayue.entity.Role;
import com.huayue.util.PageHelper;
import com.mysql.DBHelper;

/**
 * 角色
 * 
 */
@Component
public class RoleDao implements BaseDao<Role> {
    @Override
    public int insert(Role entity) {
        int successNum = 0;
        successNum += DBHelper.executeUpdate("insert into role (parentid, name, remark,dep_id) values (?,?,?,?)",
            entity.getParentid(), entity.getName(), entity.getRemark(), entity.getDep_id());
        return successNum;
    }

    @Override
    public int update(Role entity) {
        int successNum = 0;
        // 1.修改主表中的信息
        successNum += DBHelper.executeUpdate("update role set parentid=?,name=?, remark=?,dep_id=? where id=?",
            entity.getParentid(), entity.getName(), entity.getRemark(), entity.getDep_id(), entity.getId());
        return successNum;
    }

    @Override
    public int delete(Role entity) {
        return DBHelper.executeUpdate("update role set is_deleted=1 where id=?", entity.getId());
    }

    @Override
    public List<Map<String, Object>> findAll(Object... obj) {
        return DBHelper.executeQuery("select * from role where is_deleted=0");
    }

    @Override
    public List<Map<String, Object>> findPage(PageHelper page, Object... obj) {
        String sql =
            "select a.name parentname,b.*,dep.name depname from role a right JOIN role b on b.parentid=a.id left join department dep on b.dep_id=dep.id where 1=1 and b.is_deleted=0 ";
        return DBHelper.executeQuery(sql + " limit ?,? ", page.getBegin(), page.getPageSize());
    }

    @Override
    public Map<String, Object> findOne(Role entity) {
        List<Map<String, Object>> list = DBHelper.executeQuery(
            "select a.name parentname,b.*,de.name depname from role a right JOIN role b on b.parentid=a.id left join department de on de.id=b.dep_id where b.is_deleted=0 and b.id=? limit 0,1 ",
            entity.getId());
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public int count(Object... obj) {
        String sql =
            "select count(*) counts from role a right JOIN role b on b.parentid=a.id where 1=1 and b.is_deleted=0 ";
        return Integer.valueOf(DBHelper.executeQuery(sql).get(0).get("counts").toString());
    }

    public List<Map<String, Object>> findAllTopRole() {
        return DBHelper.executeQuery("select * from role where is_deleted=0 ");
    }
}
